package logic

import (
	"context"

	"go-zero-mall/app/admin/cmd/rpc/internal/svc"
	"go-zero-mall/app/admin/cmd/rpc/pd"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type AmdinListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAmdinListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AmdinListLogic {
	return &AmdinListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 管理员-查询列表
func (l *AmdinListLogic) AmdinList(in *pd.AdminListReq) (*pd.AdminListResp, error) {
	rowBuilder := l.svcCtx.UmsAdminModel.RowBuilder()
	countBuilder := l.svcCtx.UmsAdminModel.CountBuilder("*")
	if len(in.Keyword) > 0 {
		rowBuilder = rowBuilder.Where("username=?", in.Keyword)
		countBuilder = countBuilder.Where("username=?", in.Keyword)
	}
	list, err := l.svcCtx.UmsAdminModel.FindByPageParam(l.ctx, rowBuilder, in.PageNum, in.PageSize)
	if err != nil {
		return nil, errors.New("管理员-列表查询错误")
	}
	total, err := l.svcCtx.UmsAdminModel.FindCount(l.ctx, countBuilder)
	if err != nil {
		return nil, err
	}
	var d []*pd.AdminParamReq
	copier.Copy(&d, list)
	for i := 0; i < len(list); i++ {
		d[i].CreateTime = list[i].CreateTime.Unix()
		d[i].LoginTime = list[i].LoginTime.Unix()
	}
	return &pd.AdminListResp{List: d, Total: total}, nil
}
